import PostalMime from 'postal-mime';
import { extractTextFromHTML } from '~/utils';
import { summarize } from '~/utils/chat'
import { addDraft } from '~/utils/wechat'

defineNitroPlugin((nitro) => {
  nitro.hooks.hook("cloudflare:email", async ({ event, env }) => {
    const rawEmail = await new Response(event.raw).text();
    const parsedEmail = await PostalMime.parse(rawEmail);
    const html = parsedEmail.html || parsedEmail.text || '';
    const now = Date.now();
    await env.KV.put(now, html);
    const text = extractTextFromHTML(html);
    const md = await summarize(text, env.OPENROUTER_API_KEY);
    console.log(md);
    await env.KV.put(now + '_zh', html);
    await addDraft(env, {
      title: md.split('\n\n')[0].replace('# ', ''),
      content: md,
    });

  })
})
